//
//  String+Extend.swift
//  String
//
//  Created by mini on 2025/4/28.
//

import CryptoKit
import Foundation

extension String {

    // md5加密
    var md5: String {
        guard let data = data(using: .utf8) else { return "" }
        let hash = Insecure.MD5.hash(data: data)
        let md5String = hash.map { String(format: "%02hhx", $0) }.joined()
        return md5String
    }

    // 去除字符串中所有空格
    func removeAllSpaces() -> String {
        return replacingOccurrences(of: " ", with: "")
    }

    // MARK: - 图片文字组合
    func setAttributedStringWithImage(imageName: String, imageRect: CGRect, index: Int) -> NSMutableAttributedString {
        let attch = NSTextAttachment()
        attch.image = UIImage(named: imageName)
        attch.bounds = imageRect
        let string = NSAttributedString(attachment: attch)
        let titleAttr = NSMutableAttributedString(string: self)
        titleAttr.insert(string, at: index)
        return titleAttr
    }

    // MARK: - 显示不同的文字颜色
    func setAttributedDifferentTextColor(markStrAry: [String], lineSpacing: CGFloat, alignment: NSTextAlignment, colorAry: [UIColor]) -> NSMutableAttributedString {
        if isStr(self) {
            // 设置格式
            let attributedString = NSMutableAttributedString(string: self)
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.alignment = alignment
            paragraphStyle.lineSpacing = lineSpacing
            let attributes: [NSAttributedString.Key: Any] = [
                .paragraphStyle: paragraphStyle,
                .underlineStyle: NSUnderlineStyle(rawValue: 0),
            ]
            attributedString.addAttributes(attributes, range: NSRange(location: 0, length: attributedString.length))

            // 获取range 和 color
            for i in 0 ..< markStrAry.count {
                let markStr = markStrAry[i]
                guard let range = range(of: markStr) else { continue }
                let nsRange = NSRange(range, in: self)
                attributedString.addAttribute(.foregroundColor, value: colorAry[i], range: nsRange)
            }
            return attributedString
        } else {
            return NSMutableAttributedString(string: "")
        }
    }

    // MARK: - 显示不同的文字大小
    func attributedString(withParts parts: [(text: String, font: UIFont, color: UIColor)]) -> NSAttributedString {
        let attributedString = NSMutableAttributedString()
        for part in parts {
            let font = part.font
            let attributes: [NSAttributedString.Key: Any] = [
                .font: font,
                .foregroundColor: part.color,
            ]
            let partAttributedString = NSAttributedString(string: part.text, attributes: attributes)
            attributedString.append(partAttributedString)
        }
        return attributedString
    }
}
